# $Id: tserver.py 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

__version__ = "$Revision: 7557b5d4d82b $"
__author__ = "$Author: pgurumur $"

from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.http import HttpResponse
from django.shortcuts import render_to_response

from djanet.lib import stdlib, log
from djanet.termserver import forms, views
from djanet.utils import utils

register = template.Library()

@register.tag(name = 'tsform')
def do_tsform(parser, token):
   """
   {% tsform console_mapping %}
   """

   form = None
   bits = token.split_contents()
   if len(bits) == 2:
      form = bits[1]
   else:
      raise tempalte.TemplateSyntaxError("'%s' needs 2 arguments" %bits[0])

   return TemplateFormNode(form)

   """
   nodelist = parser.parse(('endvenya',))
   parser.delete_first_token()
   if len(bits) == 4:
      app = bits[1]
      model = bits[2]
      action = bits[3]
   else:
      raise template.TemplateSyntaxError("'%s' needs 4 arguments" %bits[0])

   return node.TemplateNode(app, model, action, nodelist)
   """

class TemplateFormNode(template.Node):
   def __init__(self, Form):
      super(stdlib.my_class(self), self).__init__()
      self._formName = None

      if Form:
         self._formName = Form
      else:
         raise template.TemplateSyntaxError("no form defined!")

   def render(self, context):
      retval = None
      if self._formName:
         form = None
         if self._formName == "console_mapping":
            form = forms.ConsoleForm()

         if form:
            # tmpl = template.loader.get_template(form.Meta.template)
            template = form.Meta.template
            retval = render_to_response(template, (utils.get_context(None,
               csform = form, csform_id = "csform_id",
               csform_jsid = "csform_jsid", csform_action =
               reverse(views.csmapping))))

      return retval
